<!-- 设置页 -->
<script setup lang="ts">
import {useRouter, useRoute} from 'vue-router'
import {Search} from '@element-plus/icons-vue'
import type {TabsPaneContext} from 'element-plus'
import {Server} from '@/stores/ajax'
import {GetUserState} from '@/stores/userState';
import HeaderVue from '@/components/Header.vue'
import FooterVue from '@/components/Footer.vue'
import {
    Menu as IconMenu,
    Location,
    Setting, Plus
} from '@element-plus/icons-vue'
import {reactive, ref, h, watch} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import type {UploadProps, UploadUserFile, UploadRawFile} from 'element-plus'
import {ServerUtils} from '@/serverUtils';

let user = GetUserState()
// console.log(user.uid)

const fileList = $ref<UploadUserFile[]>([
    {
        name: 'avatar.jpeg',
        url: Server.fileBaseURL + user.avatar,
    }])
let menuIndex = $ref("0")

const onMenuSelect = (key: string, keyPath: string[]) => {
    menuIndex = key
}
let userData = ref<any>({})
let privacyData = ref<any>({})
let avatarFile = $ref<UploadRawFile>()
let avatarHasChange = $ref(false)
const handleExceed: UploadProps['onExceed'] = (files) => {
    const file = files[0] as UploadRawFile
    // console.log(file)
    const fileReader = new FileReader()
    fileReader.readAsDataURL(file)
    fileReader.onload = function (e) {
        fileList[0].url = this.result as string
    }
    avatarFile = file
    avatarHasChange = true
}
let passwordData = $ref({
    password: "",
    newpassword: ""
})
const loadUserData = () => {
    userData.value = {
        gender: user.gender,
        signature: user.signature
    }
    privacyData.value = {
        name: user.name,
        tel: user.tel,
        college_class: user.college_class,
        hide_email: user.hide_email,
        hide_class: user.hide_class,
        hide_tel: user.hide_tel,
        hide_name: user.hide_name,
    }
    console.log(privacyData.value)
    fileList[0].url = Server.fileBaseURL + user.avatar
}
watch(user, loadUserData)
loadUserData()
const userDataRules = reactive<FormRules>({
    signature: [
        // {required: true, message: '请输入姓名', trigger: 'blur'},
        {min: 1, max: 150, message: '长度在1到150', trigger: 'blur'},
    ],
})
const privacyRules = reactive<FormRules>({
    name: [
        // {required: true, message: '请输入姓名', trigger: 'blur'},
        {min: 2, max: 15, message: '长度在2到15', trigger: 'blur'},
    ],
    tel: [
        // {required: true, message: '请输入电话', trigger: 'blur'},
        {min: 11, max: 11, message: '长度在11位', trigger: 'blur'},
    ],
    college_class: [
        // {required: true, message: '请输入电话', trigger: 'blur'},
        {min: 3, max: 10, message: '长度在3到10', trigger: 'blur'},
    ],
})

const privacyFormRef = $ref<FormInstance>()
const userFormRef = $ref<FormInstance>()
const submitUpdateUserData = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        for (let k of Object.keys(userData.value)) {
            if (userData.value[k] === '') userData.value[k] = undefined
        }
        if (valid) {
            await Server.post('/user/set_data', userData.value, true).then(res => {
                if (res.data && res.data.code == 0) {
                    user = res.data.return
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const submitUpdatePrivacyData = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        for (let k of Object.keys(privacyData.value)) {
            if (privacyData.value[k] === '') privacyData.value[k] = undefined
        }
        if (valid) {
            await Server.post('/user/set_data', privacyData.value, true).then(res => {
                if (res.data && res.data.code == 0) {
                    user = res.data.return
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
// console.log(user.avatar)
const submitChangeAvatar = async () => {
    if (avatarHasChange)
        await Server.axios.post('/user/change_avatar', {image: avatarFile}, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }
        ).then((res) => {
            Server.checkShowMessage(res)
        }).catch(console.log)

    avatarHasChange = false

}
const submitChangePassword = async () => {
    await Server.post('/user/change_password', passwordData, true).then(res => {
        if (res.data && res.data.code == 0) {
            passwordData.password = ""
            passwordData.newpassword = ""
        }
    })
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        return false
    }
    return true
}
</script>

<template>
    <header>
        <HeaderVue />
    </header>
    <el-container class="setting-block">
        <el-aside width="160px">
            <el-menu default-active="0" class="setting-menu"
                @select="onMenuSelect">
                <el-menu-item index="0" class='fh'>
                    <el-icon>
                        <Setting />
                    </el-icon>
                    <span>基本设置</span>
                </el-menu-item>
                <el-menu-item index="1" class='fh'>
                    <el-icon>
                        <Setting />
                    </el-icon>
                    <span>资料隐私</span>
                </el-menu-item>
            </el-menu>
        </el-aside>
        <el-container>
            <el-main>
                <div class='fh'>
                    <!-- s0 {{{ -->
                    <div v-if="menuIndex == '0' && user.uid"
                        style="max-width: 570px;padding-right: 100px;">
                        <div
                            style="display: flex; flex-flow: column nowrap;">
                            <el-space direction="vertical"
                                :size="10">
                                <el-upload
                                    class="avatar-uploader"
                                    :auto-upload="false"
                                    accept='image/png, image/jpeg'
                                    :limit="1"
                                    v-model:file-list="fileList"
                                    :on-exceed="handleExceed">
                                    <span
                                        class="el-upload-list__item-actions">
                                        更换头像
                                    </span>
                                    <template
                                        #file="{file}">
                                        <div
                                            style="margin-top: -31px;">
                                            <el-image
                                                shape="square"
                                                style="width: 120px;height: 120px;"
                                                :size="50"
                                                :src="file.url"
                                                fit="cover" />
                                        </div>
                                    </template>
                                </el-upload>
                                <el-button
                                    :disabled="!avatarHasChange"
                                    style="margin: 0 auto;"
                                    type="primary"
                                    @click="submitChangeAvatar">
                                    保存头像
                                </el-button>
                            </el-space>
                        </div>
                        <el-form ref="userFormRef"
                            :model="userData"
                            :rules="userDataRules"
                            label-width="120px" status-icon>
                            <div class="fhs">
                                <el-form-item label="id">
                                    <div
                                        style="width: 100px;">
                                        <span>{{
                                                user.uid
                                        }}</span>
                                    </div>
                                </el-form-item>

                                <el-form-item label="邮箱">
                                    <span>{{
                                            user.email
                                    }}</span>
                                </el-form-item>
                            </div>
                            <div class="fhs">
                                <el-form-item label="用户名">
                                    <div
                                        style="width: 100px;">
                                        <span>{{
                                                user.user_name
                                        }}</span>
                                    </div>
                                </el-form-item>
                                <el-form-item label="身份">
                                    {{ !user.is_guide &&
                                            !user.is_admin ? "一般用户"
                                            : ""
                                    }}
                                    <span
                                        v-if="user.is_guide"
                                        style="margin-right: 5px;vertical-align: middle;">导游</span>
                                    <span
                                        v-if="user.is_admin"
                                        style="margin-right: 5px;vertical-align: middle;">管理员
                                    </span>
                                    <el-link
                                        v-if="user.is_admin"
                                        href="/admin"
                                        :underline='false'>
                                        进入管理员面板
                                    </el-link>
                                </el-form-item>
                            </div>
                            <el-form-item label="性别"
                                prop="resource">
                                <el-radio-group
                                    v-model="userData.gender">
                                    <el-radio label="男" />
                                    <el-radio label="女" />
                                    <el-radio label="未知" />
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="修改密码">
                                <el-row :gutter="10">
                                    <el-col :span="10">
                                        <el-input
                                            v-model="passwordData.password"
                                            type="password"
                                            placeholder="原密码"
                                            autocomplete="off" />
                                    </el-col>
                                    <el-col :span="10">
                                        <el-input
                                            v-model="passwordData.newpassword"
                                            type="password"
                                            placeholder="新密码"
                                            autocomplete="off" />
                                    </el-col>
                                    <el-col :span="4">
                                        <el-button
                                            type="primary"
                                            @click="submitChangePassword()">
                                            修 改
                                        </el-button>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <el-form-item label="自我介绍"
                                prop="signature">
                                <el-input
                                    v-model="userData.signature"
                                    type="text"
                                    autocomplete="off" />
                            </el-form-item>

                            <div style="display: flex;">
                                <el-button type="primary"
                                    style="width: 60%;margin: 0 auto; margin-top: 20px;"
                                    @click="submitUpdateUserData(userFormRef)">
                                    保 存
                                </el-button>
                            </div>
                        </el-form>

                        <div style="height: 10vh;"></div>
                    </div>
                    <!-- // }}} -->

                    <!-- s1 {{{ -->
                    <div v-if="menuIndex == '1' && user.uid"
                        style="max-width: 600px;padding-right: 100px;">

                        <el-form ref="privacyFormRef"
                            :model="privacyData"
                            :rules="privacyRules"
                            label-width="120px" status-icon>
                            <div class="fhs label1">
                                <span>隐藏</span>
                            </div>
                            <el-form-item label="邮箱"
                                prop="email">
                                <div class="fhs input-item">
                                    <el-input
                                        v-model="user.email"
                                        type="text"
                                        autocomplete="off"
                                        class="input-min"
                                        disabled />
                                    <el-switch
                                        v-model="privacyData.hide_email"
                                        size="size" />
                                </div>
                            </el-form-item>
                            <el-form-item label="姓名"
                                prop="name">
                                <div class="fhs input-item">
                                    <el-input
                                        v-model="privacyData.name"
                                        type="text"
                                        autocomplete="off"
                                        class="input-min" />
                                    <el-switch
                                        v-model="privacyData.hide_name"
                                        size="size" />
                                </div>
                            </el-form-item>
                            <el-form-item label="电话"
                                prop="tel">
                                <div class="fhs input-item">
                                    <el-input
                                        v-model="privacyData.tel"
                                        type="text"
                                        autocomplete="off"
                                        class="input-min" />
                                    <el-switch
                                        v-model="privacyData.hide_tel"
                                        size="size" />
                                </div>
                            </el-form-item>
                            <el-form-item label="班级"
                                prop="class">
                                <div class="fhs input-item">
                                    <el-input
                                        v-model="privacyData.college_class"
                                        type="text"
                                        autocomplete="off"
                                        class="input-min" />
                                    <el-switch
                                        v-model="privacyData.hide_class"
                                        size="size" />
                                </div>
                            </el-form-item>

                            <div style="display: flex;">
                                <el-button type="primary"
                                    style="width: 60%;margin: 0 auto; margin-top: 20px;"
                                    @click="submitUpdatePrivacyData(privacyFormRef)">
                                    保 存
                                </el-button>
                            </div>
                        </el-form>

                        <div style="height: 10vh;"></div>
                    </div>
                    <!-- // }}} -->

                </div>
            </el-main>
        </el-container>
    </el-container>


</template>

<style scoped lang="scss">
.setting-block {
    background-color: white;
    width: 1080px;
    margin: 0 auto;

    .setting-menu {
        height: 100%;
    }

    .input-min {
        width: 160px;
        margin-right: 60px;
    }

    .label1 {
        justify-content: end;
        margin-bottom: 10px;
        color: #666;

    }

}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.input-search {
    width: 600px;
}

.box-card {
    width: 250px;
}

span {
    display: inline;
}

.avatar-uploader {
    width: 120px;
    height: 120px;
    margin: 0 auto;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    /* transition: var(--el-transition-duration-fast); */
}

.el-upload-list__item-actions {
    position: absolute;
    top: 0;
    line-height: 120px;
    left: 0;
    z-index: 10;
    text-align: center;
    width: 120px;
    color: #0000;
}

@keyframes fadenum {
    0% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.el-upload-list__item-actions:hover {
    color: #fff;
    font-weight: 600;
    background-color: #0003;
    animation: fadenum 0.3s 1;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}
</style>

